package de.hs_mannheim.vem.ajchat;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class TcpConnection {
	protected interface SockOp {
		void operateOnSocket(ObjectOutputStream oos) throws Exception;
	}

	public static InetAddress[] getIPs() throws SocketException {
		final List<InetAddress> ips = new LinkedList<InetAddress>();
		for (final NetworkInterface netIf : Collections.list(NetworkInterface.getNetworkInterfaces())) {
			for (final InetAddress iAddr : Collections.list(netIf.getInetAddresses())) {
				ips.add(iAddr);
			}
		}
		return ips.toArray(new InetAddress[ips.size()]);
	}

	private final InetSocketAddress	target;

	public TcpConnection(final InetSocketAddress address) {
		target = address;
	}

	protected synchronized void doSockOp(final SockOp op) throws Exception {
		final Socket sock = new Socket();
		OutputStream os = null;
		try {
			sock.connect(target);
			os = sock.getOutputStream();
			final ObjectOutputStream oos = new ObjectOutputStream(os);
			op.operateOnSocket(oos);

			oos.flush();
			os.flush();

			while (sock.getInputStream().read() != -1) {
			} // Wait until to Receiver has stopped reading

			sock.close();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				sock.close();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
	}
}
